import { useEffect, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { Menu } from "antd";
import { findAllBreadcrumb, getOpenKeys, searchRoute } from "@/utils/util";
import { connect } from "react-redux";
import type { MenuProps } from "antd";
import Logo from "./components/Logo";
import { setBreadcrumbList } from "@/redux/modules/global/action";
import { cloneDeep } from "lodash-es";
import { deepLoopFloat } from "@/routers/utils/menuHelper";
import "./index.less";

const LayoutMenu = (props: any) => {
	const { pathname } = useLocation();
	const navigate = useNavigate();

	const { setBreadcrumbList } = props;
	const { backMenuList } = props.permission;
	const { isCollapse } = props.global;

	const [selectedKeys, setSelectedKeys] = useState<string[]>([pathname]);
	const [openKeys, setOpenKeys] = useState<string[]>([]);
	const [menuList, setMenuList] = useState<any[]>([]);
	// const [loading, setLoading] = useState(false);

	/** Function */

	const onOpenChange = (openKeys: string[]) => {
		if (openKeys.length === 0 || openKeys.length === 1) return setOpenKeys(openKeys);
		const latestOpenKey = openKeys[openKeys.length - 1];
		if (latestOpenKey.includes(openKeys[0])) return setOpenKeys(openKeys);
		setOpenKeys([latestOpenKey]);
	};

	const clickMenu: MenuProps["onClick"] = ({ key }: { key: string }) => {
		const route = searchRoute(key, props.menuList);
		if (route.isLink) window.open(route.isLink, "_blank");
		navigate(key);
	};

	/** Effect */

	useEffect(() => {
		setSelectedKeys([pathname]);
		isCollapse ? null : setOpenKeys(getOpenKeys(pathname));
	}, [pathname, isCollapse]);

	useEffect(() => {
		setBreadcrumbList(findAllBreadcrumb(backMenuList));
		// set menu
		let menus = cloneDeep(backMenuList);
		setMenuList(deepLoopFloat(menus));
	}, [backMenuList]);

	return (
		<div className="menu">
			{/* <Spin spinning={loading} tip="Loading..."> */}
			<Logo></Logo>
			<Menu
				theme="dark"
				mode="inline"
				triggerSubMenuAction="click"
				openKeys={openKeys}
				selectedKeys={selectedKeys}
				items={menuList}
				onClick={clickMenu}
				onOpenChange={onOpenChange}
			></Menu>
			{/* </Spin> */}
		</div>
	);
};

const mapStateToProps = (state: any) => state;
const mapDispatchToProps = { setBreadcrumbList };
export default connect(mapStateToProps, mapDispatchToProps)(LayoutMenu);
